package com.jvyou.mybatis.builder.parser;

import com.jvyou.mybatis.exception.JvyouMybatisException;
import com.jvyou.mybatis.utils.string.StringUtils;
import org.dom4j.Element;

import java.util.List;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/20 11:41
 * @Description Mappers 节点处理器
 */
public class MappersNodeHandler implements XmlConfigNodeHandler {
    @Override
    public void handle(Element element, XmlConfigContext context) {
        parseMapper(element, context);
        parsePackage(element, context);
    }

    @SuppressWarnings("unchecked")
    private static void parseMapper(Element element, XmlConfigContext context) {
        List<Element> mapperEls = element.elements(MAPPER);
        for (Element mapperEl : mapperEls) {
            String className = mapperEl.attributeValue(CLASS);
            String resource = mapperEl.attributeValue(RESOURCE);
            String file = mapperEl.attributeValue(FILE);
            if (!StringUtils.isEmpty(className)) {
                context.addMapper(className);
            }
            if (!StringUtils.isEmpty(resource)) {
                context.addResource(resource);
            }
            if (!StringUtils.isEmpty(file)) {
                context.addFile(file);
            }
        }
    }

    @SuppressWarnings("unchecked")
    private static void parsePackage(Element element, XmlConfigContext context) {
        List<Element> packageEls = element.elements(PACKAGE);
        for (Element packageEl : packageEls) {
            String packageName = packageEl.attributeValue(NAME);
            if (StringUtils.isEmpty(packageName)) {
                throw new JvyouMybatisException("配置文件的mapper节点的package属性不能为空");
            }
            context.addPackage(packageName);
        }
    }
}
